package com.jt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.pojo.Dept;
import com.jt.pojo.Menu;
import com.jt.pojo.Result;
import com.jt.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("system/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;
    @GetMapping("/getMenuList")
    public Result getMenuList(){
        List<Menu> list = menuService.getMenuList();
        return Result.success( list);
    }

    //新增菜单
    @PostMapping("/insert")
    public Result insert(@RequestBody Menu menu) {
        if (Objects.isNull(menu.getParent())) {
            menu.setParent("0");
            menu.setName(menu.getTitle());
            boolean save = menuService.save(menu);
            if (save) {
                return Result.success("添加成功");
            }
            return Result.error("添加失败");
        } else {
            menu.setName(menu.getTitle());
            boolean b = menuService.save(menu);
            if (b) {
                return Result.success("添加成功");
            }
            return Result.error("添加成功");
        }

    }

    //删除
    @GetMapping("/delete")
    public Result delete(String id) {
        List<String> ids = menuService.list(new QueryWrapper<Menu>().eq("parent", id)).stream().map(Menu::getId).collect(Collectors.toList());
        ids.add(id);
        boolean b = menuService.removeByIds(ids);
        if (b) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    //修改
    @PostMapping("/update")
    public Result update(@RequestBody Menu menu) {
        boolean b = menuService.updateById(menu);
        if (b) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }
}
